layui.use(['layer','jquery','form','table'],function () {
    let form = layui.form;
    let layer = layui.layer;
    let $ = layui.$;
    let table = layui.table;
    let user = JSON.parse(localStorage.getItem('user'));
    //隐藏右键框
    $(document).click(function () {
        parent.$('.rightMenu').hide();
    });
    //返回功能
    $('#goBack').click(function () {
        parent.tabParentChange(3);
    })
    //刷新功能
    $('#refresh').click(function () {
        location.reload();
    });
    //查询所有课程分类（下拉框结构）
    getCourseClassSelect();
    //查询所有课程分类（树结构）
    getCourseClassTree();
    //查询所有课程
    getAllCourses({display: 1});
    function getCourseClassSelect() {
        $.ajax({
            url : '/courseClass/getAllJsCourseClassSelect',
            dataType: 'json',
            success: function (data) {
                var allCourseClass = data.data;
                //进行layui下拉框赋值
                for (var i = 0; i < allCourseClass.length; i++) {
                    $('#courseClass').append('<option value="'+allCourseClass[i].id+'">'+allCourseClass[i].name+'</option>');
                }
                form.render();
            }
        });
    }
    function getCourseClassTree() {
        var setting = {
            data: {
                simpleData: {
                    enable: true,  //true 、 false 分别表示 使用 、 不使用 简单数据模式
                    idKey: "id",  //节点数据中保存唯一标识的属性名称
                    pIdKey: "parentId",    //节点数据中保存其父节点唯一标识的属性名称
                    rootPId: -1  //用于修正根节点父节点数据，即 pIdKey 指定的属性值
                },
                key: {
                    name: "name"  //zTree 节点数据保存节点名称的属性名称  默认值："name"
                }
            },
            view: {
                dblClickExpand: false
            },
            check: {
                enable : false,  //true 、 false 分别表示 显示 、不显示 复选框或单选框
                nocheckInherit:true  //当父节点设置 nocheck = true 时，设置子节点是否自动继承 nocheck = true
            },
            callback: {
                onClick: zTreeOnClick,//点击树节点展示对应table信息
                onRightClick: OnRightClick
            }
        };
        getAllJsCourseClassTree();
        function getAllJsCourseClassTree(){
            $.ajax({
                url: '/courseClass/getAllJsCourseClassTree',
                dataType: 'json',
                success: function (data) {
                    //部门树的渲染
                    zTree = $.fn.zTree.init($("#courseTree"), setting, data.data);//初始化树
                    zTree.expandAll(true);    //true 节点全部展开、false节点收缩
                }
            });
        }


        rMenu = $("#rMenu");

        //点击节点
        function zTreeOnClick() {
            var nodes = zTree.getSelectedNodes();
            var node = nodes[0];
            //查询点击的分类节点对应的多个课程
            courseClass(node.id);
        }
        function courseClass(classId) {
            if(classId == 0){
                courseTreeNodeClick();
                return;
            }
            courseTreeNodeClick(classId);
        }
        function courseTreeNodeClick(classId) {
            $.ajax({
                url: '/course/getCoursesByClassId',
                data:{classId: classId,display: 1},
                dataType: 'json',
                success: function (data) {
                    coursesTableRender(data.data);
                }
            });
        }
        //树的一系列配置
        function OnRightClick(event, treeId, treeNode) {
            if (!treeNode && event.target.tagName.toLowerCase() != "button" && $(event.target).parents("a").length == 0) {
                zTree.cancelSelectedNode();
                showRMenu("root", event.clientX, event.clientY);
            } else if (treeNode && !treeNode.noR) {
                zTree.selectNode(treeNode);
                showRMenu("node", event.clientX, event.clientY);
            }
        }
        function showRMenu(type, x, y) {
            if (type=="root") {
                $("#m_del").hide();
            } else {
                $("#m_del").show();
            }
            y += document.body.scrollTop;
            x += document.body.scrollLeft;


            rMenu.css({'display':'block','position':'fixed',"top":y+"px", "left":x+"px", "visibility":"visible"});

            $("body").bind("mousedown", onBodyMouseDown);
        }
        function hideRMenu() {
            if (rMenu) rMenu.css({"visibility": "hidden"});
            $("body").unbind("mousedown", onBodyMouseDown);
        }
        function onBodyMouseDown(event){
            if (!(event.target.id == "rMenu" || $(event.target).parents("#rMenu").length>0)) {
                rMenu.css({"visibility" : "hidden"});
            }
        }
        //增加节点
        $('#m_add').click(function () {
            var nodes = zTree.getSelectedNodes();
            var node = nodes[0];
            layer.prompt({
                title: '添加课程分类',
                area: ['300px', '100px']
            }, function(value, index, elem){
                addCourseClass(value,node.id);
                layer.close(index)
            });
        });
        //删除节点
        $('#m_del').click(function () {
            var nodes = zTree.getSelectedNodes();
            var node = nodes[0];
            var count = getClassLowerCourseCount(node.id);
            if(count > 0){
                layer.msg('此分类下还有课程 不能删除');
                return;
            }
            if(node.isParent){
                layer.msg('此分类下还有课程分类 不能删除');
            }else{
                var layerIndex = layer.confirm('确定要删除"' + node.name + '"么?', {
                    btn: ['确定','取消'],
                    title: '删除课程分类',
                }, function(){
                    deleteCourseClass(node.id);
                    layer.close(layerIndex);
                });
            }

        })

        //修改节点
        $('#m_edit').click(function () {
            var nodes = zTree.getSelectedNodes();
            var node = nodes[0];
            layer.prompt({
                title: '修改课程分类名称',
                area: ['300px', '100px'],
                value: node.name
            }, function(value, index, elem){
                updateCourseClass(value,node.id);
                layer.close(index)
            });
        })
        function addCourseClass(className,id) {
            $.ajax({
                url: '/courseClass/addCourseClass',
                type: 'post',
                dataType: 'json',
                data: {
                    name: className,
                    parentId: id,
                    createId: user.data.userId,
                },
                success: function (data) {
                    if(data.data.id != null){
                        layer.msg('添加成功');
                        getAllJsCourseClassTree();
                    }
                }
            });
        }
        function deleteCourseClass(id) {
            $.ajax({
                url: '/courseClass/deleteCourseClass',
                type: 'post',
                dataType: 'json',
                data: {
                    id: id,
                },
                success: function (data) {
                    if(data.data){
                        layer.msg('删除成功');
                        getAllJsCourseClassTree();
                    }
                }
            });
        }
        function updateCourseClass(className, id) {
            $.ajax({
                url: '/courseClass/updateCourseClass',
                type: 'post',
                dataType: 'json',
                data: {
                    name: className,
                    id: id,
                    updateId: user.data.userId,
                },
                success: function (data) {
                    if(data.data){
                        layer.msg('修改成功');
                        getAllJsCourseClassTree();
                        getAllCourses({display: 1});
                    }
                }
            });
        }
        function getClassLowerCourseCount(classId){
            var courseCount ;
            $.ajax({
                url: '/course/getClassLowerCourseCount',
                dataType: 'json',
                data: {
                    classId: classId,
                    display: 1
                },
                async: false,
                success: function (data) {
                    if(data.data > 0){
                        courseCount = data.data
                    }
                }
            });
            return courseCount;
        }
    }

    //根据课程价格、课程分类、课程名称查询 课程
    form.on('submit(search)',function (obj) {
        getAllCourses(obj.field);
        return false;
    });
    //修改上架状态
    form.on('switch(courseStatus)',function (data) {
        if(data.elem.checked){
            updateCourseStatus(data.value,2);
        }else{
            updateCourseStatus(data.value,3);
        }
    });
    //高级检索
    $('#courseSearch').click(function () {
        layer.open({
            type : 2,
            title : "高级检索",
            area : [ '780px', '450px' ],
            shade : 0,
            offset: 'auto',
            content:'course-search.html',
        })
    });
    function updateCourseStatus(courseId,courseStatus) {
        $.ajax({
            url: '/course/updateCourseStatus',
            dataType: 'json',
            data:{
                courseStatus: courseStatus,
                courseId: courseId
            },
            type: 'post',
            success: function (data) {
                if(data.data){
                    if(courseStatus == 3){
                        layer.msg('下架成功')
                    }else if(courseStatus == 2){
                        layer.msg('上架成功')
                    }
                }
            }
        });
    }
    function getAllCourses(course) {
        $.ajax({
            url: '/course/getCourses',
            data: course,
            dataType: 'json',
            success: function (data) {
                coursesTableRender(data.data);
            }
        });
    }
    coursesTableRender = function coursesTableRender(courses) {
        table.render({
            elem: '#courseTable',
            title: '课程列表',
            data: courses,
            limit: 10,
            toolbar: '#course_thead',
            page:{
                layout:['count','prev','page','next','limit','skip','refresh'],
                //limits:[3,6,9],
                first:"首页",
                last:"尾页",
            },
            cols: [[
                {type:'checkbox'},
                {title:'序号',align:'center',templet:function(data){
                    return data.LAY_INDEX;
                }},
                {field:"",title:"课程图片",align:'center',templet:function(data){
                    return '<img src="'+ data.url +'" />';
                }},
                {field:"courseName",title:"课程名称",align:'center'},
                {field:"account",title:"创建人",align:'center'},
                {field:"courseNprice",title:"课程现价",align:'center',templet:function(data){
                    return '￥' + data.courseNprice;
                }},
                {field:"",title:"上架状态",align:'center',templet:function(data){
                    if(data.courseStatus == 2){
                        return '<input type="\checkbox\" value="'+data.courseId +'" lay-skin=\"switch\" lay-text=\"上架|下架"\ checked lay-filter="courseStatus" />';
                    }else if(data.courseStatus == 3){
                        return '<input type=\"checkbox\" value="'+data.courseId +'" lay-skin=\"switch\" lay-text=\"上架|下架"\ lay-filter="courseStatus">';
                    }
                }},
                {field:"className",title:"课程分类",align:'center'},
                {field:"saleNum",title:"课程销量",align:'center'},
                {field:"",title:"审核状态",align:'center',templet:function(data){
                    var result;
                    if(data.result == 1){
                        result = '审核通过'
                    }else if(data.result == 2){
                        result = '待审核'
                    }else if(data.result == 3){
                        result = '已驳回'
                    }
                    return '<p>'+result+'</p><a href="javascript:auditDetails(' + data.courseId+');" style="color: #00B83F;" >审核详情</a>';
                }},
                {field:'',title:"操作",align:'center',toolbar: '#operation'}
            ]]
        });
    }
    //表头工具栏点击
    table.on('toolbar(courseTable)',function (obj) {
        if(obj.event == 'addCourse'){
            parent.addTab(17);
        }
    })
    //表内工具栏点击
    table.on('tool(courseTable)',function (obj) {
        //删除课程
        if(obj.event == 'deleteCourseTable'){
            var layerIndex = layer.confirm('确定要删除"' + obj.data.courseName + '"么?', {
                btn: ['确定','取消'],
                title: '删除课程分类',
            }, function(){
                deleteCourse(obj.data.courseId);
                layer.close(layerIndex);
            });
        }else if(obj.event == 'selectCourseTable'){
            layer.open({
                type: 2,
                title: '查看课程详情',
                content: 'course-details.html',
                area:["95%","99%"],
                scrollbar: false,
                offset:'auto',
                shade: 0.4,
                btn:['确定','取消'],
                yes:function(index,layero){
                    layer.close(index);
                },
                success:function (layero, index) {
                    var childHtml = layero.find('iframe').contents();
                    getCurrentCourse(childHtml,obj.data);
                }
            });
        }else if(obj.event == 'updateCourseTable'){
            layer.open({
                type: 2,
                title: '修改课程信息',
                content: 'update-course-message.html',
                area:['800px','520px'],
                scrollbar: false,
                offset:'auto',
                shade: 0.4,
                success:function (layero, index) {
                    var childHtml = layero.find('iframe').contents();
                    $.ajax({
                        url: '/course/getCourseByCourseId',
                        dataType: 'json',
                        data: {courseId: obj.data.courseId, commentType: 2},
                        success: function (data) {
                            childHtml.find('#coursePrimary').val(data.data.coursePrimary);
                            childHtml.find('#courseIntro').val(data.data.courseIntro);
                            childHtml.find('#courseId').val(obj.data.courseId);
                            childHtml.find('#courseName').val(obj.data.courseName);
                            childHtml.find('#courseNprice').val(obj.data.courseNprice);
                            childHtml.find('#coursePrice').val(obj.data.courseNprice);
                            childHtml.find('#status').val(data.data.courseStatus);
                            childHtml.find('#updateId').val(user.data.userId);
                        }
                    })
                },
                end: function () {
                    getAllCourses({display: 1});
                }
            });
        }else if(obj.event == 'courseLog'){
            layer.open({
                type: 2,
                title: '课程日志',
                content: '/course/courseManage/courseList/course-log.html',
                area:['95%','99%'],
                scrollbar: false,
                offset:'auto',
                shade: 0.4,
                btn:['确定','取消'],
                yes:function(index,layero){
                    layer.close(index);
                },
            })
        }
    })
    function getCurrentCourse(childHtml, course) {
        $.ajax({
            url: '/course/getCourseByCourseId',
            dataType: 'json',
            data:{courseId: course.courseId,commentType: 2},
            success: function (data) {
                var newCourse = data.data;
                $.ajax({
                    url: '/log/addLog',
                    type: 'post',
                    dataType: 'json',
                    data: {
                        tableName: 'js_course',
                        type: 5,
                        userId: user.data.userId,
                        remark: '查看课程详情信息',
                        logType: 2
                    },
                    success: function(data){
                        if(data.data.logId != null){
                            childHtml.find('#courseName').text(newCourse.courseName);
                            childHtml.find('#createDate').text(newCourse.createDate);
                            childHtml.find('#account').text(newCourse.account);
                            childHtml.find('#courseNprice').text(parseFloat(newCourse.courseNprice) + '元');
                            childHtml.find('#coursePrimary').text(newCourse.coursePrimary);
                            childHtml.find('#className').text(newCourse.className);
                            childHtml.find('#likeNum').text(newCourse.likeNum);
                            childHtml.find('#collectNum').text(newCourse.collectNum);
                            childHtml.find('#commentNum').text(newCourse.commentNum);
                            childHtml.find('#courseIntro').text(newCourse.courseIntro);
                            childHtml.find('#courseInfo').text(newCourse.courseInfo);
                            childHtml.find('#url').attr('src',newCourse.url);
                            childHtml.find('#courseUrl').attr('src',newCourse.courseUrl);
                            childHtml.find('#trueName').val(user.data.trueName);
                            childHtml.find('#courseId').val(course.courseId);
                            childHtml.find('.account').val(user.data.account);
                        }
                    }
                });

            }
        });
    }
    function deleteCourse(courseId) {
        $.ajax({
            url: '/course/deleteCourseByCourseId',
            type: 'post',
            dataType: 'json',
            data: {courseId: courseId,display: 2},
            success: function (data) {
                if(data.data){
                    $.ajax({
                        url: '/log/addLog',
                        type: 'post',
                        dataType: 'json',
                        data: {
                            tableName: 'js_course',
                            type: 3,
                            userId: user.data.userId,
                            remark: '删除课程',
                            logType: 2
                        },
                        success: function(data){
                            if(data.data.logId != null){
                                layer.msg('删除成功');
                                getAllCourses({display: 1});
                            }
                        }
                    });
                }
            }
        });
    }
    auditDetails = function auditDetails(courseId) {
        layer.open({
            type : 2,
            title : "审核详情",
            area : [ '780px', '450px' ],
            shade : 0,
            offset: 'auto',
            content:'course-audit-details.html',
            success: function (layero,index) {
                var childHtml = layero.find('iframe').contents();
                childHtml.find('#courseId').val(courseId);
            }
        })
    }
})